var myChartMap = {};var myOptionMap = {};
$(document).ready(function() {
	$(".echarts").dblclick(echartsConfig);
	$(".echarts").dblclick();
});
function echartsConfig(options){
	
	//div上的属性值封装
	var data = new Object();
	var _defaults = {
        srcEle: this,
        id:$(this).attr('id'),
        echarts_type:$(this).attr('echarts-type'),
        echarts_title:$(this).attr('echarts-title'),
        echarts_subtitle:$(this).attr('echarts-subtitle'),
        echarts_link:$(this).attr('echarts-link'),
        echarts_sublink:$(this).attr('echarts-sublink'),
        echarts_toolbox:$(this).attr('echarts-toolbox'),
        echarts_theme:$(this).attr('echarts-theme'),
        echarts_x_axis_name:$(this).attr('echarts-x-axis-name'),
        echarts_y_axis_name:$(this).attr('echarts-y-axis-name'),
        echarts_datazoom:$(this).attr('echarts-datazoom'),
        echarts_regression:$(this).attr('echarts-regression'),
        echarts_degree:$(this).attr('echarts-degree'),
        echarts_url:$(this).attr('echarts-url'),
        echarts_socket:$(this).attr('echarts-socket'),
        echarts_measure_range:$(this).attr('echarts-measure-range'),
        echarts_split_number:$(this).attr('echarts-split-number'),
        echarts_axis_label_show:$(this).attr('echarts-axis-label-show')
    };
    var opts = $.extend(true, _defaults, options);
    data.id=opts.id;
    data.type=opts.echarts_type;
    data.title=opts.echarts_title;
    data.subtitle=opts.echarts_subtitle;
    data.link=opts.echarts_link;
    data.sublink=opts.echarts_sublink;
    data.isNeedToolBox=opts.echarts_toolbox;
    data.theme=opts.echarts_theme;
    data.xaxisName=opts.echarts_x_axis_name;
    data.yaxisName=opts.echarts_y_axis_name;
    data.isNeedDataZoom=opts.echarts_datazoom;
    data.regression=opts.echarts_regression;
    data.degree=opts.echarts_degree;
    data.url=opts.echarts_url;
    data.socket=opts.echarts_socket;
    data.measureRange=opts.echarts_measure_range;
    data.splitNumber=opts.echarts_split_number;
    data.axisLabelShow=opts.echarts_axis_label_show;
    //传入参数
    data.serializeParameters=$("form").serializeArray();
    var paraMap = {};
    for (var i = 0; i < data.serializeParameters.length; i++) {
    	paraMap[data.serializeParameters[i].name]=data.serializeParameters[i].value;
    }
    data.parameters=paraMap;
    //散点图通过前台会更加方便
    if(data.type=='scatter'){
    	echartsStat(data);
    //其他图表通过后台解析GsonOption
    }else if(data.type=='gauge'){
    	echartsGauge(data);
    }else if(data.type=='liquidFill'){
    	echartsLiquidFill(data);
    }else{
	    jQuery.ajax({
			headers : {
				'Accept' : 'application/json',
				'Content-Type' : 'application/json'
			},
			type : "POST",
			url : data.url,
			data : JSON.stringify(data),
			dataType : 'text',
			success : function(message, tst, jqXHR) {
				// 基于准备好的dom，初始化echarts实例
			    var myChart = echarts.init(document.getElementById(data.id),data.theme);
			    myOption = eval('(' + message + ')');
			    // 使用刚指定的配置项和数据显示图表。
			    myChart.setOption(myOption);
			    myChartMap[data.id]=myChart;
			    myOptionMap[data.id]=myOption;
			    if(data.socket!=''){
			    	var ws = new SockJS(data.socket);  
			        ws.onopen = function () {
			            console.log('Info: connection opened.');  
			        };  
			        ws.onmessage = function (event) { 
			        	var jsonObj = JSON.parse(event.data);
			            
			            console.log(jsonObj);
			        	for (var i=0;i<myOptionMap[data.id].series.length;i++){
			        		for(var key in jsonObj){
				                  if(key!='xxx'){
				                	myOptionMap[data.id].series[i].data.shift();
				                	myOptionMap[data.id].series[i].data.push(jsonObj[myOptionMap[data.id].series[i].name]);
				                  }else{
				                	myOptionMap[data.id].xAxis[0].data.shift();
				                	myOptionMap[data.id].xAxis[0].data.push(jsonObj[key]);
				                  }
				            }
			        		
			        	}
			        	myChartMap[data.id].setOption(myOptionMap[data.id]);
			         	//console.log('Received: ' + event.data); 
			        };
			        ws.onclose = function (event) {  
			            console.log('Info: connection closed.');  
			            console.log(event);  
			        };
			    }
			    //给图表相关区域添加click事件
			    if(data.type=='bar'||data.type=='pie'){
			    	myChart.on('click', function (params) {
				    	console.log(params.seriesName);
				    	console.log(params.name);
				    	console.log(params.value);
				    });
			    }
			}
	    });
    }
}

function echartsGauge(data){
	var option = {
	    tooltip : {
	        formatter: "{a} <br/>{b}: {c}"+data.xaxisName
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            mark : {show: false},
	            restore : {show: false},
	            saveAsImage : {show: true}
	        }
	    },
	    series : [
	        {
	            name:data.title,
	            type:'gauge',
	            z: 3,
	            min:0,
	            max: data.measureRange,
	            splitNumber:data.splitNumber,
	            axisLine: {            // 坐标轴线
	                lineStyle: {       // 属性lineStyle控制线条样式
	                    width: 10
	                }
	            },
	            axisTick: {            // 坐标轴小标记
	                length :15,        // 属性length控制线长
	                lineStyle: {       // 属性lineStyle控制线条样式
	                    color: 'auto'
	                }
	            },
	             axisLabel: {           // 坐标轴文本标签，详见axis.axisLabel
	                show:data.axisLabelShow,
	              	textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
	                    color: 'auto'
	                }
	            },
	            splitLine: {           // 分隔线
	                length :20,         // 属性length控制线长
	                lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
	                    color: 'auto'
	                }
	            },
	            title : {
	                textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
	                    fontWeight: 'bolder',
	                    fontSize: 20,
	                    fontStyle: 'italic'
	                }
	            },
	            detail : {
	                textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
	                    fontWeight: 'bolder'
	                },
	                formatter:'{value}'+data.xaxisName
	            },
	            data:[{value: 0, name: data.subtitle}]
	        }
	    ]
	 };
	// 基于准备好的dom，初始化echarts实例
	var myChart = echarts.init(document.getElementById(data.id),data.theme);
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    
    var ws = new SockJS(data.socket);  
    ws.onopen = function () {
        console.log('Info: connection opened.');  
    };  
    ws.onmessage = function (event) { 
    	option.series[0].data[0].value = event.data;
    	myChart.setOption(option, true);
     	console.log('Received: ' + event.data); 
    };
    ws.onclose = function (event) {  
        console.log('Info: connection closed.');  
        console.log(event);  
    };
}

function echartsLiquidFill(data){
	var option = {
	    series : [
	        {
	        	name: data.title,
	        	type:'liquidFill',
	            data:[0]
	        },
	    ],
	    tooltip: {
	        show: data.isNeedToolBox
	    }
	 };
	// 基于准备好的dom，初始化echarts实例
	var myChart = echarts.init(document.getElementById(data.id),data.theme);
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    
    var ws = new SockJS(data.socket);  
    ws.onopen = function () {
        console.log('Info: connection opened.');  
    };  
    ws.onmessage = function (event) { 
    	//option.series[0].data[0].value = event.data;
    	myChart.setOption({
    	    series : [
    	  	        {
    	  	           data:[(event.data*0.01).toFixed(2)]
    	  	        }
    	  	    ]
    	  	 });
     	console.log('Received: ' + (event.data*0.01).toFixed(2)); 
    };
    ws.onclose = function (event) {  
        console.log('Info: connection closed.');  
        console.log(event);  
    };
}

//散点图以及回归方程
function echartsStat(data){
    jQuery.ajax({
		headers : {
			'Accept' : 'application/json',
			'Content-Type' : 'application/json'
		},
		type : "POST",
		url : data.url,
		data : JSON.stringify(data),
		dataType : 'json',
		success : function(message, tst, jqXHR) {
			// See https://github.com/ecomfe/echarts-stat
			if(data.regression=='polynomial'){
				var myRegression = ecStat.regression(data.regression,message,data.degree);
				console.log("多项式阶数为："+data.degree);
			}else{
				var myRegression = ecStat.regression(data.regression,message);
			}

			myRegression.points.sort(function(a, b) {
			    return a[0] - b[0];
			});

			var option = {
			    title: {
			        text: data.title,
			        subtext: data.subtitle,
			        left: 'center'
			    },
			    tooltip: {
			        trigger: 'axis',
			        axisPointer: {
			            type: 'cross'
			        }
			    },
			    xAxis: {
			        type: 'value',
			        splitLine: {
			            lineStyle: {
			                type: 'dashed'
			            }
			        },
			    },
			    yAxis: {
			        type: 'value',
			        min: 1.5,
			        splitLine: {
			            lineStyle: {
			                type: 'dashed'
			            }
			        },
			    },
			    series: [{
			        name: 'scatter',
			        type: 'scatter',
			        label: {
			            emphasis: {
			                show: true,
			                position: 'left',
			                textStyle: {
			                    color: 'blue',
			                    fontSize: 16
			                }
			            }
			        },
			        data: message
			    }, {
			        name: 'line',
			        type: 'line',
			        showSymbol: false,
			        data: myRegression.points,
			        markPoint: {
			            itemStyle: {
			                normal: {
			                    color: 'transparent'
			                }
			            },
			            label: {
			                normal: {
			                    show: true,
			                    position: 'left',
			                    formatter: myRegression.expression,
			                    textStyle: {
			                        color: '#333',
			                        fontSize: 14
			                    }
			                }
			            },
			            data: [{
			                coord: myRegression.points[myRegression.points.length - 1]
			            }]
			        }
			    }]
			};
			// 基于准备好的dom，初始化echarts实例
			var myChart = echarts.init(document.getElementById(data.id),data.theme);
		    // 使用刚指定的配置项和数据显示图表。
		    myChart.setOption(option);
		}
    });
}
